const ResourceModel = require("./../models/resource");
const RoleModel = require("./../models/role");
const Joi = require("joi");
const UserModel = require("./../models/user");
const {
  secretKey,
  expirationTime,
  tokenKey,
} = require("./../config/auth.json");
const { setLocalsState } = require("../handler");

module.exports.queryAuthTree = async (req, res, next) => {
  try {
      const docs = await ResourceModel.find({});
      const data = docs.map((doc) => doc.toJSON());
      const root = data.filter((item) => !item.parentId);
      const find = (item, parent) => {
        parent.find((parentItem) => {
          if (parentItem._id.toJSON() === item.parentId.toJSON()) {
            parentItem.children = parentItem.children || [];
            parentItem.children.push(item);
          } else {
            if (parentItem.children) {
              find(item, parentItem.children);
            }
          }
        });
      };
  
      data.forEach((item) => {
        if (!item.parentId) {
          return;
        }
        find(item, root);
      });
  
      setLocalsState(res, {
        authTree: root,
      });

      next();
    } catch (e) {
      next(e);
    }
};

module.exports.resourceAdd = async (req, res, next) => {
  const schema = Joi.object({
    name: Joi.string().required(),
    path: Joi.string().required()
  });
  const result = schema.validate(req.body, {
    abortEarly: false,
    allowUnknown: true,
  });
  try {
    if (result.error) {
      throw new Error(result.error.details[0].message);
    }
    const cateModel = new ResourceModel({
      ...result.value
    });
    const cateDoc = await ResourceModel.create(cateModel);
    if (!cateDoc) {
      throw new Error("创建分类失败");
    }
    next();
  } catch (e) {
    next(e);
  }
};

module.exports.destoryResource = async (req, res, next) => {
  const schema = Joi.object({
    id: Joi.string().required(),
  });
  const result = schema.validate(req.query, {
    abortEarly: false,
    allowUnknown: true,
  });
  try {
    if (result.error) {
      throw new Error(result.error.details[0].message);
    }
    const cateDoc = await ResourceModel.findByIdAndDelete(result.value.id);
    if (!cateDoc) {
      throw new Error("删除分类失败");
    }
    next();
  } catch (e) {
    next(e);
  }
};

module.exports.roleAdd = async (req, res, next) => {
  const schema = Joi.object({
    name: Joi.string().min(2).max(10).required(),
    resourceId: Joi.array().items(Joi.string())
  });
  const result = schema.validate(req.body, {
    abortEarly: false,
    allowUnknown: true,
  });
  try {
    if (result.error) {
      throw new Error(result.error.details[0].message);
    }
    const roleModel = new RoleModel({
      ...result.value,
      resource: result.value['resourceId[]']
    });
    const roleDoc = await RoleModel.create(roleModel);
    if (!roleDoc) {
      throw new Error("创建角色失败");
    }
    next();
  } catch (e) {
    next(e);
  }
};

module.exports.roleRecord = async (req, res, next) => {
  try {
    const data = await RoleModel.paginate({});

    setLocalsState(res, {
      roleRecord: data
    });

    next();
  } catch (e) {
    next(e);
  }
};

module.exports.userRecord = async (req, res, next) => {
  try {
    const data = await UserModel.paginate({});

    setLocalsState(res, {
      userRecord: data
    });

    next();
  } catch (e) {
    next(e);
  }
};
